import Loading from '@/components/Loading'
import MainLayout from '@/components/MainLayout'
import NotFound from '@/components/NotFound'
import { ROUTER_PATHS_PUBLIC } from '@/constants/global'
import loadable from '@loadable/component'
import type { RouteObject } from 'react-router-dom'
import { createBrowserRouter, createHashRouter, RouterProvider } from 'react-router-dom'

// type ILazyLoadFn = Parameters<typeof loadable>[0]
type ILazyOpts = Parameters<typeof loadable>[1]

/** 👇 @loadable/component 的默认配置 👇 */
const lazyCmpDefaultOpts: ILazyOpts = { fallback: <Loading /> }

/** 👇 调用 @loadable/component 懒加载组件, 并预添加默认配置 👇 */
function lazy(loadFn: any, opts?: ILazyOpts) {
  const LazyComponent = loadable(loadFn, { ...lazyCmpDefaultOpts, ...opts })
  return <LazyComponent />
}

export const SLASH_ROUTE_CHILDREN: RouteObject[] = [
  { path: ROUTER_PATHS_PUBLIC.HOME, element: lazy(() => import('@/pages/Home')) },
]

const routes: RouteObject[] = [
  /** 👇 以 "/*" 结尾表示开启模糊匹配 👇 */
  { path: `${ROUTER_PATHS_PUBLIC.LOGIN}/*`, element: lazy(() => import('@/pages/Login')) },
  { path: `${ROUTER_PATHS_PUBLIC.REGISTER}/*`, element: lazy(() => import('@/pages/Register')) },
  {
    path: ROUTER_PATHS_PUBLIC.SLASH,
    element: <MainLayout />,
    children: [
      // { index: true, element: lazy(() => import('@/pages/Home')) },
      ...SLASH_ROUTE_CHILDREN,
      { path: ROUTER_PATHS_PUBLIC.OTHER, element: <NotFound /> },
    ],
  },
]

const createRouterOpts: Parameters<typeof createHashRouter>[1] = {
  basename: '/',
  /** 👇 解决 react-router-dom@6.28 控制台有警告的问题 👇 */
  // [Bug]: react-router-dom@6.28 shows
  // v7_fetcherPersist
  // v7_normalizeFormMethod
  // v7_partialHydration
  // v7_relativeSplatPath
  // v7_skipActionErrorRevalidation
  // warning but such future flag is not present #12245
  future: {
    v7_fetcherPersist: true,
    v7_normalizeFormMethod: true,
    v7_partialHydration: true,
    v7_relativeSplatPath: true,
    v7_skipActionErrorRevalidation: true,
  },
}
export const router =
  import.meta.env.VITE_ROUTER_MODE === 'history'
    ? createBrowserRouter(routes, createRouterOpts)
    : createHashRouter(routes, createRouterOpts)

export default function RouterEntry() {
  /** 👇 解决 react-router-dom@6.28 控制台有警告的问题 👇 */
  // [Bug]: react-router-dom@6.28 shows v7_startTransition warning but such future flag is not present #12245
  return <RouterProvider router={router} future={{ v7_startTransition: true }} />
}
